package com.cms.action;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.cms.bean.CreditBean;
import com.cms.sqlMap.SqlMapConfig;
import com.ibatis.sqlmap.client.SqlMapClient;

public class CreditAction extends DispatchAction {

	private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());
	private SqlMapClient sqlMap = SqlMapConfig.getSqlMapInstance();
	
	public ActionForward insert(ActionMapping mapping,
				     ActionForm form,
				     HttpServletRequest request,
				     HttpServletResponse response) throws Exception {
		
		CreditBean bean = (CreditBean) form;
		log.debug("#####################");
		log.debug(bean.getCust_nm());
		log.debug(bean.getCust_no());
		log.debug(bean.getTelno());
		log.debug(bean.getDiv_type());
		log.debug(bean.getBuy_type());
		log.debug(bean.getTelco());
		log.debug(bean.getAudlt_yn());
		log.debug(bean.getLawer_nm());
		log.debug(bean.getLawer_cust_no());
		log.debug(bean.getLawer_telno());
		log.debug("#####################");
		
		try {
			sqlMap.startTransaction();
			sqlMap.insert("Cms.credit-insert", bean);
			sqlMap.commitTransaction();
			
			request.setAttribute("resultCode", "1000");
		} catch (SQLException e) {
			log.debug(e.toString());
		} finally {
			try {
				sqlMap.endTransaction();
			} catch(SQLException e) {}
		}
		
		return mapping.findForward("insert");
	}
	
	
	@SuppressWarnings("rawtypes")
	public ActionForward list(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		CreditBean bean = (CreditBean) form;
		
		int pageCount = 10;
		int currentPage = (bean.getCurrentPage() == 0) ? 1 : bean.getCurrentPage();
		bean.setPageCount(pageCount);
		bean.setCurrentPage((currentPage - 1) * pageCount);
		
		List list = sqlMap.queryForList("Cms.credit-list", bean);
		bean = (CreditBean)sqlMap.queryForObject("Cms.credit-list-totalCount", bean);
		
		bean.setCurrentPage(currentPage);
		bean.setTotalCount((int) Math.ceil((double)bean.getTotalCount() / (double)pageCount));
		request.setAttribute("list", list);
		request.setAttribute("bean", bean);
		
		return mapping.findForward("list");
	}
}
